package com.zh.mybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.mybatis.domain.book.dto.BookReqParam;
import com.zh.mybatis.domain.book.entity.Book;
import com.zh.mybatis.domain.book.BookRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ZH
 * @date 20:47 2021/11/16
 */
@AllArgsConstructor
@RestController
@RequestMapping("/book")
public class BookController {
    private final BookRepository bookRepository;

    @PostMapping
    public String addBook(@RequestBody Book book) {
        Assert.notNull(book,"提交数据不能为空");

        bookRepository.insert(book);
        return "success: id="+ book.getId();
    }

    @PutMapping("/{id}")
    public String updateBook(@PathVariable Long id, @RequestBody Book book) {
        Assert.notNull(book,"提交数据不能为空");

        Book dbBook = bookRepository.selectById(id);
        BeanUtils.copyProperties(book, dbBook);
        bookRepository.updateById(dbBook);
        return "success";
    }

    @DeleteMapping("/{id}")
    public String removeBook(@PathVariable Long id) {
        bookRepository.deleteById(id);
        return "success";
    }

    @GetMapping("/page")
    public List<Book> findPage(BookReqParam param) {
        Page<Book> page = new Page<>(param.getNum(), param.getSize());

        Page<Book> pageData = bookRepository.selectPage(page, new QueryWrapper<>());
        return pageData.getRecords();
    }

}
